<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery-3.1.1.min.js"></script>
		<style type="text/css">
			body{margin: 0; padding: 0; font-size: 14px;}
			h1{font-weight: normal;}
			#cvs{border: 1px solid #ccc; position: absolute; left: 50%; margin-left: -300px; top: 15%;}
			#box{position: absolute; left: 50%; margin-left: -400px; top: 15%; -webkit-user-select: none;}
			#btn{margin-bottom: 20px;}
		</style>
	</head>
	<body>
		<canvas id="cvs" width="500" height="500"></canvas>
		<div id="box">
			<button id="btn">开始游戏</button><br />
			模式 <select class="select">
				<option value="1">简单</option>
				<option value="2">困难</option>
			</select>
			<p>长度：<span id="len">1</span></p>
			<p>难度：<span id="level">1</span></p>
		</div>
	</body>
</html>
<script type="text/javascript">
$(function(){
	var oBtn = document.getElementById("btn");
	var oLen = document.getElementById("len");
  	var cvs = document.getElementById("cvs");
	var ctx = cvs.getContext('2d');
	ctx.strokeStyle = '#ccc';
	var size = 20;
	var timerId = 0;
	var isHaveFood = true;
	var x = parseInt(Math.random()*24);
	var y = parseInt(Math.random()*24);
	var time = 150;
	var level = 1;
	var isDefeat = false;
	var isSimple = true;
	
	var snake = [
		[0,0],
	];
	
	var dir = 'xia';
	
	oBtn.onclick = function(){
		$(".temp").remove();
		if ($(".select").val() == 2) {
			isSimple = false;
		}
		start(time);
		draw();
	}
	init();
	function init () {
		var pattern = '';
		var ptext = '';
		doselect();
		$(".select").change(function(){
		  	doselect();
		})
		
		function doselect () {
			$(".temp").remove();
			if ($(".select").val() == 1) {
				pattern = '简单';
				ptext = '简单模式可穿墙';
			}else{
				ptext = '困难模式不可穿墙';
				pattern = '困难';
			}
			$("<div class='temp'><h1>"+pattern+"</h1><p>"+ptext+"</p></div>").css({
				position: 'absolute',
				top: '30%',
				left: '45%',
				'text-align': 'center',
			}).appendTo($("body"));
		}
	}
	function start (t) {
		clearInterval(timerId);
		timerId = setInterval(function(){
			if (isSimple) {
				check();
			}
			createNewSnake(dir,judge);
			draw();
		},t);
	}
	
	function draw () {
		ctx.clearRect(0,0,500,500);
		createFood();
		for (var i=0; i<25; i++) {
			for (var j=0; j<25; j++) {
				ctx.strokeRect(i*size,j*size,size,size);
			}
		}
		for (var i=0; i<snake.length; i++) {
			ctx.beginPath();
			ctx.fillStyle = 'seagreen';
			ctx.fillRect(snake[i][0]*size,snake[i][1]*size,size,size);
			ctx.closePath();
		}
	}
	//键盘事件
	$(document).keydown(function(ev){
		if (snake[0][0] >24 || snake[0][0]<0 || snake[0][1]>24 || snake[0][1]<0) {
			return;
		}
		if (ev.keyCode == 37 && dir != 'you'){
			dir = 'zuo';
		}
		if (ev.keyCode == 39 && dir != 'zuo'){
			dir = 'you';
		}
		if (ev.keyCode == 38 && dir != 'xia'){
			dir = 'shang';
		}
		if (ev.keyCode == 40 && dir != 'shang'){
			dir = 'xia';
		}
	})
	
	function createNewSnake (dir,fn) {
		var tempArr = copy(snake);
		if (dir == 'zuo') {
			snake[0][0] -= 1;
		}
		if (dir == 'you') {
			snake[0][0] += 1;
		}
		if (dir == 'shang') {
			snake[0][1] -= 1;
		} 
		if (dir == 'xia') {
			snake[0][1] += 1;
		}
		for (var i=1; i<snake.length; i++) {
			snake[i][0] = tempArr[i-1][0];
			snake[i][1] = tempArr[i-1][1];
		}
		fn&&fn();
	}
	//判断
	function judge () {
		for (var i=0; i<snake.length; i++) {
			//判断吃到食物
			if (snake[i][0] == x && snake[i][1] == y) {
				var a = [snake[snake.length-1][0],snake[snake.length-1][1]];
				snake.push(a);		//小蛇加长1格
				var tempLen = parseInt(oLen.innerHTML)+1;
				oLen.innerHTML = tempLen;
				createPosition();	//重新生成食物
			}
			//判断失败
			if (snake.length>2 && i!=0 && snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]) { isDefeat = true;}
			if (!isSimple) {
				if (snake[0][0]<0 || snake[0][0]>24 || snake[0][1]<0 || snake[0][1]>24) { isDefeat = true; }
			}
		}
		if (snake.length >= level*5) {
			time -= 15;
			start(time);
			var oLevel = document.getElementById("level");
			oLevel.innerHTML = parseInt(oLevel.innerHTML)+1;
			level++;
		}
		if (isDefeat) {
			alert('您失败了!');
			clearInterval(timerId);
			location.reload();
		}
	}
	
	//随机生成食物
	function createFood () {
		ctx.beginPath();
		ctx.fillStyle = 'red';
		ctx.fillRect(x*size,y*size,size,size);
		ctx.closePath();
	}
	//生成食物随机坐标,并且不能再贪吃蛇的体内生成
	function createPosition () {
		var temX = parseInt(Math.random()*24);
		var temY = parseInt(Math.random()*24);
		for (var i=0; i<snake.length; i++) {
			if (temX == snake[i][0] && temY == snake[i][1]) {
				createPosition();
			}else{
				x = temX;
				y = temY;
			}
		}
	}
	
　	function copy(arr) {
        var newArr = [];
        var len = arr.length;
        for (let i=0; i < len; i++) {
            if (arr[i] instanceof Array){
                newArr[i] = copy(arr[i]);
            }
            else newArr[i] = arr[i];
        }
        return newArr;
    }
	
	function check () {
		for (var i=0; i<snake.length; i++) {
			if (snake[i][0] == 25 && (snake[i][1]>=0 || snake[i][1]<=24) && dir=='you') { snake[i][0] = -1; }
			if (snake[i][0] == -1 && (snake[i][1]>=0 || snake[i][1]<=24) && dir=='zuo') { snake[i][0] = 25; }
			if (snake[i][1] == -1 && (snake[i][0]>=0 || snake[i][0]<=24) && dir=='shang') { snake[i][1] = 25; }
			if (snake[i][1] == 25 && (snake[i][0]>=0 || snake[i][0]<=24) && dir=='xia') { snake[i][1] = -1; }
		}
	}
	/*var arr = createArray2(10,12);
	arr[0][0] = 1;
	console.log(arr);

	function createArray2 (x,y) {
		var arr = new Array();
		for (var i=0; i<x; i++) {
			arr[i] = new Array();
			for (var j=0; j<y; j++) {
				arr[i][j] = 0;
			}
		}
		return arr;
	}*/
})
</script>
